package com.jackiepenghe.testvideocompress

import android.app.ComponentCaller
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.util.Log
import android.view.View
import androidx.core.net.toUri
import com.jackiepenghe.testvideocompress.databinding.ActivityMainBinding
import com.sscl.baselibrary.activity.BaseViewBindingAppCompatActivity
import com.sscl.baselibrary.files.FileProviderUtil
import com.sscl.baselibrary.files.FileSystemUtil
import com.sscl.baselibrary.files.FileSystemUtil.onStartActivity
import com.sscl.baselibrary.files.FileSystemUtil.openSystemFile
import com.sscl.baselibrary.files.FileSystemUtil.setOnFileSelectedListener
import com.sscl.baselibrary.files.FileUtil
import com.sscl.baselibrary.utils.ToastUtil

class MainActivity : BaseViewBindingAppCompatActivity<ActivityMainBinding>() {

    private val onFileSelectedListener =
        object : FileSystemUtil.OnFragmentActivityFileSelectedListener {
            override fun fileSelected(resultCode: Int, uri: Uri?, filePath: String?) {
                if (resultCode == RESULT_CANCELED) {
                    ToastUtil.toastLong(this@MainActivity, "用户取消选择文件")
                    binding.filePathTv.text = ""
                    binding.fileNameTv.text = ""
                    return
                }
                if (uri == null && filePath == null) {
                    ToastUtil.toastLong(this@MainActivity, "选择的文件为空")
                    binding.filePathTv.text = ""
                    binding.fileNameTv.text = ""
                    return
                }
                Log.i(TAG, "fileSelected: uri path = ${uri?.path} filePath = $filePath")

                if (filePath != null) {
                    binding.filePathTv.text = filePath
                    binding.fileNameTv.text = filePath.substringAfterLast("/")
                } else if (uri != null) {
                    val filePathFromUri = FileProviderUtil.getPath(uri)
                    if (filePathFromUri == null) {
                        ToastUtil.toastLong(this@MainActivity, "获取文件路径失败")
                        binding.filePathTv.text = ""
                        binding.fileNameTv.text = ""
                        return
                    }
                    binding.filePathTv.text = filePathFromUri
                    binding.fileNameTv.text = filePathFromUri.substringAfterLast("/")
                }
            }

        }
    private val onClickListener = View.OnClickListener {
        when (it) {
            binding.selectFileBtn -> {
                openSystemFile()
            }

            binding.compressBtn -> {
                val filePath = binding.filePathTv.text.toString()
                if (filePath.isEmpty()) {
                    ToastUtil.toastLong(this@MainActivity, "请先选择要压缩的文件")
                    return@OnClickListener
                }
                val outputPath =
                    "${FileUtil.sdCardCacheDir!!.absolutePath}/${
                        binding.fileNameTv.text.toString()
                            .substringBeforeLast(".") + "_compressed.mp4"
                    }"
                Log.i(TAG, "outputPath: $outputPath")

                showCompressingDialog()
                VideoCompressor.compressVideo1(filePath, outputPath) {
                    if (it) {
                        ToastUtil.toastLong(this@MainActivity, "压缩成功")
                    } else {
                        ToastUtil.toastLong(this@MainActivity, "压缩失败")
                    }
                }
            }
        }
    }

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 实现方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    /**
     * 标题栏的返回按钮被按下的时候回调此方法
     */
    override fun titleBackClicked(): Boolean {
        return false
    }

    /**
     * 在设置布局之前需要进行的操作
     */
    override fun doBeforeSetLayout() {

    }

    /**
     * 在设置布局之后，进行其他操作之前，所需要初始化的数据
     */
    override fun doBeforeInitOthers() {
        hideTitleBar()
    }

    /**
     * 初始化控件数据
     */
    override fun initViewData(savedInstanceState: Bundle?) {
    }

    /**
     * 初始化其他数据
     */
    override fun initOtherData() {
    }

    /**
     * 设置DataBinding
     * 可在此处设置binding的viewModel或观察者等操作
     */
    override fun setBinding() {
    }

    /**
     * 初始化事件
     */
    override fun initEvents() {
        setOnFileSelectedListener(onFileSelectedListener)
        binding.selectFileBtn.setOnClickListener(onClickListener)
        binding.compressBtn.setOnClickListener(onClickListener)
    }

    /**
     * 在最后进行的操作
     */
    override fun doAfterAll() {
        checkFileManagePermission()
    }

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 重写方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    override fun onStart() {
        super.onStart()
        onStartActivity()
    }

    override fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        data: Intent?,
        caller: ComponentCaller
    ) {
        super.onActivityResult(requestCode, resultCode, data, caller)
        Log.i(TAG, "onActivityResult: 1")
    }

    @Suppress("DeprecatedCallableAddReplaceWith")
    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.i(TAG, "onActivityResult: 2")
    }

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     *
     * 私有方法
     *
     * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

    /**
     * 检查是否有读写外部存储的权限
     * 没有权限则申请权限
     */
    private fun checkFileManagePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // 先判断有没有权限
            if (Environment.isExternalStorageManager()) {
                Log.i(TAG, "checkFileManagePermission: true")
                return
            }
            val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
            intent.data = "package:$packageName".toUri()
            startActivityForResult(intent, 0)
            return
        }
        Log.i(TAG, "checkFileManagePermission: pass")
    }

    /**
     * 显示压缩中对话框
     */
    private fun showCompressingDialog() {

    }
}